package com.yangjun.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.yangjun.common.excel.DataBaseExcelContext;
import com.yangjun.dao.mybatis.mapper.report.ReportMapper;
import com.yangjun.entity.report.AppGTIDReportEntity;
import com.yangjun.entity.report.AppPageTypeFlowMailEntity;
import com.yangjun.entity.report.AppSalesReportEntity;
import com.yangjun.entity.report.MailEntity;
import com.yangjun.entity.report.SourceKeywrodReportEntity;
import com.yangjun.entity.report.SearchKeywordAppReportEntity;
import com.yangjun.entity.report.SearchKeywordGoodsReportEntity;
import com.yangjun.entity.report.SearchKeywordKzoneGoodsReportEntity;
import com.yangjun.entity.report.SearchKeywordKzoneReportEntity;
import com.yangjun.entity.report.SearchKeywordWebReportEntity;
import com.yangjun.entity.report.SearchKeywordZixunReportEntity;
import com.yangjun.entity.report.SeoChannelFlowSalesReportEntity;
import com.yangjun.entity.report.SeoProductFlowReportEntity;
import com.yangjun.entity.report.SeoProductSalesReportEntity;
import com.yangjun.entity.report.WebKzoneReportEntity;
import com.yangjun.entity.report.WebSalesReportEntity;
import com.yangjun.utils.FileUtils;
import com.yangjun.utils.ZipUtil;
import com.yangjun.utils.export.ExportExcel;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import jxl.Workbook;
import jxl.write.WritableWorkbook;

@Service
public class MailService {
    private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private MailEntity mailEntity;
	@Autowired
	private ReportMapper reportMapper;
	@Autowired
	private DataBaseExcelContext context;
	@Value("${mail.excel}")
    private String reportTmpFiles;
	//临时报表文件夹
	public void sendAppGTIDReport(String date){
		String reportName = "APP个推ID报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
        //chenjunwen@360kad.com
		String receivers = "125960563@qq.com";
		if(createAppGTIDReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	public void sendWebKzoneReport(String date){
		String reportName = "PC_WAP广告位报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
        //chenjunwen@360kad.com
		String receivers = "125960563@qq.com,295993130@qq.com";
		if(createWebKzoneReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	public void sendWebSearchKeywordGoodsReport(String date){
		String reportName = "WEB搜索关键词商品报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
        //chenjunwen@360kad.com
		String receivers = "125960563@qq.com,chenjunwen@360kad.com";
		if(createWebSearchKeywordGoodsReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	
	public void sendWebSearchKeywordReport(String date){
		String reportName = "WEB搜索关键词报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,chenjunwen@360kad.com";
		if(createWebSearchKeywordReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	public void sendKzoneGoodsReport(String date){
		String reportName = "推荐区块商品报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,chenjunwen@360kad.com";
		if(createKzoneGoodsReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	public void sendKzoneReport(String date){
		String reportName = "推荐区块报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,chenjunwen@360kad.com";
		if(createKzoneReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	
	public void sendWebSearchKeywordZiXunReport(String date){
		String reportName = "WEB关键词咨询报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,chenjunwen@360kad.com";
		if(createWebSearchKeywordZiXunReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	
	public void sendWebSalesReport(String date){
		String reportName = "WEB订单销售报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,273756496@qq.com,574870774@qq.com,614546563@qq.com";
//		String receivers = "125960563@qq.com";
		if(createWebSalesReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	public void sendAppSalesReport(String date){
		String reportName = "App订单销售报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,2115934491@qq.com,2719923821@qq.com,454747887@qq.com";
//		String receivers = "125960563@qq.com";
		if(createAppSalesReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	
	public void sendSEOSourceKeywordReport(String deminsion,String beginDate,String endDate,Boolean compress){
		//很多中文报表名发送不出去，还没解决
		String reportName = "SEO关键词日报表";
		String fileName = beginDate+"-"+endDate+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,773107655@qq.com,kadseo@163.com";
//		String receivers = "125960563@qq.com";
		if(createSEOSourceKeywrodReport(deminsion,beginDate,endDate,reportName,fileName,fileFullPath)){
			if(compress){
				String zipName = fileName.replaceAll(".xls",".zip");
				String zipFileFullPath = reportTmpFiles+zipName;
				ZipUtil.zip(fileFullPath, zipName);
				send(zipName,zipFileFullPath,reportName,receivers);
				FileUtils.deleteFile(zipFileFullPath);
			}else{
				send(fileName,fileFullPath,reportName,receivers);
			}
//			FileUtils.deleteFile(fileFullPath);
		}
	}
	
	public void sendSEMSourceKeywordReport(String deminsion,String beginDate,String endDate,Boolean compress){
		//很多中文报表名发送不出去，还没解决
		String reportName = null;
		if("week".equals(deminsion)){
			reportName = "关键词订单销售周报表";
		}else if("month".equals(deminsion)){
			reportName = "关键词订单销售月报表";
		}else{
			reportName = "关键词订单销售日报表";
		}
		
		String fileName = beginDate+"-"+endDate+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,273756496@qq.com,574870774@qq.com,614546563@qq.com";
//		String receivers = "125960563@qq.com";
		if(createSEMSourceKeywrodReport(deminsion,beginDate,endDate,reportName,fileName,fileFullPath)){
			if(compress){
				String zipName = fileName.replaceAll(".xls",".zip");
				String zipFileFullPath = reportTmpFiles+zipName;
				ZipUtil.zip(fileFullPath, zipName);
				send(zipName,zipFileFullPath,reportName,receivers);
				FileUtils.deleteFile(zipFileFullPath);
			}else{
				send(fileName,fileFullPath,reportName,receivers);
			}
//			FileUtils.deleteFile(fileFullPath);
		}
	}
	public void sendAppSearchKeywordReport(String date){

		String reportName="APP搜索关键词报表";
		String fileName = reportName+"_"+date+".xlsx";
        String fileFullPath = reportTmpFiles + fileName;
		//发送邮件
		String receivers = "125960563@qq.com,chenjunwen@360kad.com";
		if(createAppSearchKeywordReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	public void sendAppPageTypeFlowReport(String date){
		
		//报表名称
		String reportName="App页面类型流量报表";
        String fileName = reportName+"_" + date + ".xlsx";
        //存放路径
        String fileFullPath = reportTmpFiles + fileName;
		//发送邮件,zhongzhimei@360kad.com
		String receivers = "125960563@qq.com";
		if(createAppPageTypeFlowReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	public void sendSeoProductFlowReport(String date){
		String reportName = "SEO商品流量报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,773107655@qq.com,kadseo@163.com";
		if(createSeoProductFlowReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	public void sendSeoProductSalesReport(String date){
		String reportName = "SEO商品销售报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,773107655@qq.com,kadseo@163.com";
		if(createSeoProductSalesReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	
	public void sendSeoChannelFlowSalesReport(String date){
		String reportName = "SEO渠道流量销售报表";
		String fileName = reportName+"_"+date+".xls";
        String fileFullPath = reportTmpFiles + fileName;
		String receivers = "125960563@qq.com,773107655@qq.com,kadseo@163.com";
		if(createSeoChannelFlowSalesReport(date,reportName,fileName,fileFullPath)){
			send(fileName,fileFullPath,reportName,receivers);
			FileUtils.deleteFile(fileFullPath);
		}
	}
	
	
	private Boolean createAppGTIDReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<AppGTIDReportEntity> entityList = reportMapper.queryAppGTIDReport(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","用户ID","设备ID","个推ID"};
			String[] fields={"dateDay","utmMedium","kuserid","juid","gtclientid"};
			ExportExcel<AppGTIDReportEntity> export = new ExportExcel<AppGTIDReportEntity>();
			//生成Excel
			export.fillExcel(workbook, AppGTIDReportEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
		}
	private Boolean createWebKzoneReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<WebKzoneReportEntity> entityList = reportMapper.queryWebKzoneReport(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","区块","访客数","点击数","平均访问时长","退出率","跳出率"};
			String[] fields={"dateDay","platform","visitKzone","uv","pv","avgVisit","exitRate","jumpRate"};
			ExportExcel<WebKzoneReportEntity> export = new ExportExcel<WebKzoneReportEntity>();
			//生成Excel
			export.fillExcel(workbook, WebKzoneReportEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
		}
	private Boolean createWebSearchKeywordGoodsReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<SearchKeywordGoodsReportEntity> entityList = reportMapper.queryWebSearchKeywordGoodsReport(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","搜素关键词","类型","商品ID","访客数","点击数","订单数","加入购物车数","需求登记数","电话回拨数"};
			String[] fields={"dateDay","platform","searchkeyword","type","productid","visitors","clicks","orderCount",
					"addToCardTimes","demandRegistrationTimes","faxCallBackTimes"};
			ExportExcel<SearchKeywordGoodsReportEntity> export = new ExportExcel<SearchKeywordGoodsReportEntity>();
			//生成Excel
			export.fillExcel(workbook, SearchKeywordGoodsReportEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
		}
	private Boolean createWebSearchKeywordReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<SearchKeywordWebReportEntity> entityList = reportMapper.queryWebSearchKeywordReport(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","搜素关键词","访客数","搜索次数","点击数","着落人数","跳出人数","退出人数","订单数","加入购物车数","需求登记数","电话回拨数","推荐点击数",
					"推荐加入购物车数","推荐需求登记数","推荐电话回拨数","推荐订单数"};
			String[] fields={"dateDay","platform","searchkeyword","visitors","searchTimes","clicks","landing","jumpers","exiters","orderCount",
					"addToCardTimes","demandRegistrationTimes","faxCallBackTimes","rcClicks","rcAddToCardTimes","rcDemandRegistrationTimes",
					"rcFaxCallBackTimes","rcOrderCount"};
			ExportExcel<SearchKeywordWebReportEntity> export = new ExportExcel<SearchKeywordWebReportEntity>();
			//生成Excel
			export.fillExcel(workbook, SearchKeywordWebReportEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}
	private Boolean createKzoneGoodsReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<SearchKeywordKzoneGoodsReportEntity> entityList = reportMapper.queryKzoneGoodsReport(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","区块","搜素关键词","商品ID","访客数","点击数","订单数"};
			String[] fields={"dateDay","platform","kzone","searchkeyword","productid","visitors","clicks","orderCount"};
			ExportExcel<SearchKeywordKzoneGoodsReportEntity> export = new ExportExcel<SearchKeywordKzoneGoodsReportEntity>();
			//生成Excel
			export.fillExcel(workbook, SearchKeywordKzoneGoodsReportEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}
	private Boolean createKzoneReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<SearchKeywordKzoneReportEntity> entityList = reportMapper.queryKzoneReport(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","区块","搜素关键词","访客数","点击数","订单数"};
			String[] fields={"dateDay","platform","kzone","searchkeyword","visitors","clicks","orderCount"};
			ExportExcel<SearchKeywordKzoneReportEntity> export = new ExportExcel<SearchKeywordKzoneReportEntity>();
			//生成Excel
			export.fillExcel(workbook, SearchKeywordKzoneReportEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}
	private Boolean createWebSearchKeywordZiXunReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<SearchKeywordZixunReportEntity> entityList = reportMapper.queryWebSearchKeywordZiXunReport(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","搜素关键词","页面ID","咨询数","订单数"};
			String[] fields={"dateDay","platform","keyword","pageid","askCount","orderCount"};
			ExportExcel<SearchKeywordZixunReportEntity> export = new ExportExcel<SearchKeywordZixunReportEntity>();
			//生成Excel
			export.fillExcel(workbook, SearchKeywordZixunReportEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}
	private Boolean createWebSalesReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<WebSalesReportEntity> entityList = reportMapper.queryWebSalesReport(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","部门","一级渠道","二级渠道","订单数","销售额","新客订单数","新客销售额"};
			String[] fields={"dateDay","siteName","department","utmMedium","utmSource","orders","netamt","newOrders","newNetamt"};
			ExportExcel<WebSalesReportEntity> export = new ExportExcel<WebSalesReportEntity>();
			//生成Excel
			export.fillExcel(workbook, WebSalesReportEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}
	private Boolean createAppSalesReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<AppSalesReportEntity> entityList = reportMapper.queryAppSalesReport(date);
		if(entityList!=null&&entityList.size()>0){
			try {
				//文件输出流
		        out = new FileOutputStream(new File(fileFullPath));
				//组装Excel
				WritableWorkbook workbook;
				workbook = Workbook.createWorkbook(out);
				String[] titles={"日期","平台","渠道","订单数","销售额","新客订单数","新客销售额","访客数","新访客数"};
				String[] fields={"dateDay","platform","utmSource","orders","netamt","newOrders","newNetamt","visitors","newVisitors"};
				ExportExcel<AppSalesReportEntity> export = new ExportExcel<AppSalesReportEntity>();
				//生成Excel
				export.fillExcel(workbook, AppSalesReportEntity.class,
						titles, fields,
						reportName, entityList);		
				workbook.write();
				workbook.close();
				logger.info("报表："+fileName+"生成成功！");
			} catch (Exception e) {
				logger.info("报表："+fileName+"发送失败！");
				e.printStackTrace();
				return false;
			}finally{
				//关闭流
				if(out!=null){
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
						return false;
					}
				}
			}
			return true;
		}
		return false;
	}
	private Boolean createSEOSourceKeywrodReport(String deminsion,String beginDate,String endDate,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		context.initDBExcelDefinitionReader("export");
		System.out.println(context);
		List<SourceKeywrodReportEntity> entityList = reportMapper.querySEOSourceKeywordReport(deminsion, beginDate, endDate);
		System.out.println(entityList.size());
		if(entityList!=null&&entityList.size()>0){
			try {
				//文件输出流
		        out = new FileOutputStream(new File(fileFullPath));
		        org.apache.poi.ss.usermodel.Workbook workbook = context.createExcel("semSearchKeyword", entityList);
				workbook.write(out);
				workbook.close();
				logger.info("报表："+fileName+"生成成功！");
			} catch (Exception e) {
				logger.info("报表："+fileName+"发送失败！");
				e.printStackTrace();
				return false;
			}finally{
				//关闭流
				if(out!=null){
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
						return false;
					}
				}
			}
			return true;
		}
		return false;
	}
	private Boolean createSEMSourceKeywrodReport(String deminsion,String beginDate,String endDate,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		context.initDBExcelDefinitionReader("export");
		System.out.println(context);
		List<SourceKeywrodReportEntity> entityList = reportMapper.querySEMSourceKeywordReport(deminsion, beginDate, endDate);
		System.out.println(entityList.size());
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
	        org.apache.poi.ss.usermodel.Workbook workbook = context.createExcel("semSearchKeyword", entityList);
			workbook.write(out);
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}
	private Boolean createAppSearchKeywordReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		List<SearchKeywordAppReportEntity> entityList = reportMapper.queryAppSearchKeywordReport(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","搜索关键词","访客数","搜索次数","搜索点击数","跳出人数","加入购物出数","需求登记数","订单数"};
			String[] fields={"dateDay","platform","searchKeyword","visitors","searchTimes","clicks","jumpers","addToCardTimes","demandRegistrationTimes","orderCount"};
			ExportExcel<SearchKeywordAppReportEntity> export = new ExportExcel<SearchKeywordAppReportEntity>();
			//生成Excel
			export.fillExcel(workbook, SearchKeywordAppReportEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
			return false;
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}
	private Boolean createAppPageTypeFlowReport(String date,String reportName,String fileName,String fileFullPath){
		OutputStream out = null;
		//查询数据
		List<AppPageTypeFlowMailEntity> entityList = reportMapper.queryAppPageTypeFlow(date);
		try {
			//文件输出流
	        out = new FileOutputStream(new File(fileFullPath));
			//组装Excel
			WritableWorkbook workbook;
			workbook = Workbook.createWorkbook(out);
			String[] titles={"日期","平台","类型","标识","点击数","访客数"};
			String[] fields={"dateDay","siteName","type","ident","clicks","visitors"};
			ExportExcel<AppPageTypeFlowMailEntity> export = new ExportExcel<AppPageTypeFlowMailEntity>();
			//生成Excel
			export.fillExcel(workbook, AppPageTypeFlowMailEntity.class,
					titles, fields,
					reportName, entityList);		
			workbook.write();
			workbook.close();
			logger.info("报表："+fileName+"生成成功！");
			//发送邮件
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
		}finally{
			//关闭流
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	}
	
	private Boolean createSeoProductFlowReport(String date,String reportName,String fileName,String fileFullPath){
		//查询数据
		List<SeoProductFlowReportEntity> entityList = reportMapper.querySeoProductFlowReport(date);
            ExcelWriter writer = ExcelUtil.getWriter(fileFullPath);
			List<List<String>> rowList = Lists.newArrayList();
            List<String> title = CollUtil.newArrayList("日期","平台","一级渠道","二级渠道","页面ID","访客数","浏览量","商品名称","商品编码");
            rowList.add(title);
            if(CollectionUtil.isNotEmpty(entityList)){
                for(SeoProductFlowReportEntity record : entityList){
                	List<String> row = CollUtil.newArrayList(
                			DateUtil.format(record.getDateDay(), "yyyy-MM-dd"),
                            record.getSitename(),
                            record.getUtmMedium(),
                            record.getUtmSource(),
                            record.getVisitUrlPageId(),
                            record.getVisitors().toString(),
                            record.getPv().toString(),
                            record.getWarename(),
                            record.getWareskucode()
                    );
                    rowList.add(row);
                }
            }
            writer.write(rowList);
            writer.close();
		return true;
	}
	private Boolean createSeoProductSalesReport(String date,String reportName,String fileName,String fileFullPath){
		//查询数据
		List<SeoProductSalesReportEntity> entityList = reportMapper.querySeoProductSalesReport(date);
            ExcelWriter writer = ExcelUtil.getWriter(fileFullPath);
			List<List<String>> rowList = Lists.newArrayList();
            List<String> title = CollUtil.newArrayList("日期","平台","一级渠道","二级渠道","订单编码","商品编码","商品名称","科室","销售额");
            rowList.add(title);
            if(CollectionUtil.isNotEmpty(entityList)){
                for(SeoProductSalesReportEntity record : entityList){
                	List<String> row = CollUtil.newArrayList(
                			DateUtil.format(record.getDateDay(), "yyyy-MM-dd"),
                            record.getSitename(),
                            record.getUtmMedium(),
                            record.getUtmSource(),
                            record.getOrdercode(),
                            record.getWarecode(),
                            record.getWarename(),
                            record.getDepartment(),
                            String.valueOf(record.getAmt())
                    );
                    rowList.add(row);
                }
            }
            writer.write(rowList);
            writer.close();
		return true;
	}
	private Boolean createSeoChannelFlowSalesReport(String date,String reportName,String fileName,String fileFullPath){
		//查询数据
		List<SeoChannelFlowSalesReportEntity> entityList = reportMapper.querySeoChannelFlowSalesReport(date);
            ExcelWriter writer = ExcelUtil.getWriter(fileFullPath);
			List<List<String>> rowList = Lists.newArrayList();
            List<String> title = CollUtil.newArrayList("日期","平台","一级渠道","二级渠道","访客数","浏览量","订单数","销售额");
            rowList.add(title);
            if(CollectionUtil.isNotEmpty(entityList)){
                for(SeoChannelFlowSalesReportEntity record : entityList){
                	List<String> row = CollUtil.newArrayList(
                			DateUtil.format(record.getDateDay(), "yyyy-MM-dd"),
                            record.getSitename(),
                            record.getUtmMedium(),
                            record.getUtmSource(),
                            String.valueOf(record.getVisitors()),
                            String.valueOf(record.getVisitTimes()),
                            String.valueOf(record.getOrders()),
                            String.valueOf(record.getNetamt())
                    );
                    rowList.add(row);
                }
            }
            writer.write(rowList);
            writer.close();
		return true;
	}
	
	private void send(String fileName,String fileFullPath,String title,String receivers){
		//1.创建Session,包含邮件服务器网络连接的信息
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", mailEntity.getProtocol());
		props.setProperty("mail.smtp.auth",mailEntity.getAuth());
		props.setProperty("mail.smtp.starttls.enable",mailEntity.getEnable()); 
		props.setProperty("mail.smtp.starttls.required", mailEntity.getRequired()); 
		props.setProperty("mail.smtp.port", mailEntity.getPort());
		props.setProperty("mail.smtp.host", mailEntity.getHost());
		props.setProperty("mail.smtp.user", mailEntity.getUser());
		props.setProperty("mail.smtp.password", mailEntity.getPassword());
		props.setProperty("mail.default-encoding", mailEntity.getEncoding());  
		
		Session session = Session.getDefaultInstance(props);
		
		Message message = new MimeMessage(session);
		try {
			//发送者
			message.setFrom(new InternetAddress(mailEntity.getUser()));
			//接收者
			if(StringUtils.isEmpty(receivers)){
				receivers = mailEntity.getAdministrator().toString();
			}
			message.setRecipients(RecipientType.TO, InternetAddress.parse(receivers));
			//标题
			message.setSubject(MimeUtility.encodeText(title,"UTF-8","B")); 
			//设置邮件消息内容，包含附件
			Multipart msgPart = new MimeMultipart();
			
	        // 设置正文内容
//			MimeBodyPart body = new MimeBodyPart();// 正文
//			Context ctx = new Context();
//			Map<String,String> params= Maps.newHashMap();
//			params.put("author", "杨俊");
//			params.put("email", "125960563@qq.com");
//			params.put("content", content);
//			ctx.setVariables(params);
//	        body.setContent(templateEngine.process("index",ctx), "text/html;charset=utf-8");
//	        msgPart.addBodyPart(body);
	
	        // 设置附件内容
	        MimeBodyPart attach = new MimeBodyPart(); // 附件
	        attach.attachFile(fileFullPath);
	        attach.setFileName("=?GBK?B?" + Base64.encodeBase64String(fileName.getBytes("GBK")) + "?="); 
	        msgPart.addBodyPart(attach);
	        
	        message.setContent(msgPart);
	        message.setSentDate(new Date());
	        //保存并生成最终的邮件内容 
	        message.saveChanges();
	        //发送邮件
	        Transport trans = session.getTransport();
	        trans.connect(mailEntity.getHost(), mailEntity.getUser(),mailEntity.getPassword());
	        trans.sendMessage(message, message.getAllRecipients());
	        trans.close();
			logger.info("报表："+fileName+"发送成功！");
		} catch (Exception e) {
			logger.info("报表："+fileName+"发送失败！");
			e.printStackTrace();
		}
	}
	
}
